package org.alex.nettychat.netty.custom.utils;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.util.Attribute;
import org.alex.nettychat.netty.custom.config.Attributes;
import org.alex.nettychat.netty.custom.session.Session;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : alex
 */
public class SessionUtil {
    // 用户和通道的关系
    private static final Map<Integer, Channel> userIdChannelMap = new ConcurrentHashMap<>();

    private static final Map<Integer, ChannelGroup> groupIdChannelGroupMap = new ConcurrentHashMap<>();

    /**
     * 添加Session绑定
     */
    public static void bindSession(Session session, Channel channel) {
        userIdChannelMap.put(session.getUserId(), channel);
        channel.attr(Attributes.SESSION).set(session);
    }

    /**
     * 取消Session绑定
     */
    public static void unBindSession(Channel channel) {
        userIdChannelMap.remove(getSession(channel).getUserId());
        channel.attr(Attributes.SESSION).set(null);
    }

    /**
     * 是否登录
     * @param channel
     * @return
     */
    public static boolean hasLogin(Channel channel) {
        return channel.hasAttr(Attributes.SESSION);
    }

    /**
     * 获取用户通道
     */
    public static Channel getChannel(Integer userId) {
        return userIdChannelMap.get(userId);
    }


    public static Session getSession(Channel channel) {
        return channel.attr(Attributes.SESSION).get();
    }

    public static ChannelGroup getChannelGroup(Integer groupId) {
        return groupIdChannelGroupMap.get(groupId);
    }

    public static void saveChannelGroup(Integer groupId, ChannelGroup channelGroup) {
        groupIdChannelGroupMap.put(groupId, channelGroup);
    }
}
